<script lang='ts' setup>
import { reactive, ref } from 'vue' 
import { UploadFilled } from '@element-plus/icons-vue'
import { api as ViewerApi } from 'v-viewer'
import type { FormInstance, FormRules, UploadUserFile, ElMessage } from 'element-plus' 
import type { Tree } from './AddInformation.vue'
// import TcVod from 'vod-js-sdk-v6'
import OSS from 'ali-oss';
import { ossConfig  } from '/@/api/common';
import { dirList, fileUpload } from '/@/api/commodity';
const emit = defineEmits(['refresh']);
const fileList = ref<UploadUserFile[]>([])

const ruleForm = reactive({ 
	dirId:null,
	name: '',
})
const state = reactive({
    dialog:{
        title:'',
        isShowDialog:false,
        loading:false,
    },
    treeData: [ ] as Array<Tree>,
    percentage: 0 as number,
    oss:{
        region: "oss-cn-beijing",
        // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
        accessKeyId: "LTAI5t7TcfUri3FRXU7Gtx55",
        accessKeySecret: "Kc1KZ8A3MNd6fIQdS8etUhMDZHf3zE",
        // 填写Bucket名称。
        bucket: 'konli-klys',
    },
})

const ruleFormRef = ref<FormInstance>()

const rules = reactive<FormRules<any>>({
	dirId: [{ required: true, message: '请选择上传分组', trigger: 'change' }], 
    name: [{ required: true, message: '请输入文件名', trigger: 'blur' }], 
})



const getDirList = async() => {
    state.dialog.loading = true;
    const { results } = await dirList();
    state.treeData = results;
    state.dialog.loading = false;
}


const getOssConfig = async() => {
    state.dialog.loading = true;
    const { results } = await ossConfig();
    state.oss = results;
}

// 文件改变时回调钩子
const handleChange = (file, files) => {
    // file是当前上传的文件，files是当前所有的文件，
    fileList.value = files
}

const client = new OSS({
    region: state.oss.region,
    // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
    accessKeyId: state.oss.accessKeyId,
    accessKeySecret: state.oss.accessKeySecret,
    // 填写Bucket名称。
    bucket: state.oss.bucket,
});


const submitForm =  (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.validate(async (valid, fields) => {
		if (valid) {
            const options = {
                // 获取分片上传进度、断点和返回值。
                progress: (p, cpt, res) => {
                    state.percentage = (p * 100).toFixed(2);
                },
                // 设置并发上传的分片数量。
                parallel: 4,
                // 设置分片大小。默认值为5 MB，最小值为100 KB。
                partSize: 1024 * 1024 * 5,
                // headers,
                // 自定义元数据，通过HeadObject接口可以获取Object的元数据。
                meta: { year: 2020, people: "test", temp: "konLi"  },
                headers: { "Content-Type": "video/mp4" },
                mime: "text/plain",
            };
            const fileName = Math.random().toString(36).slice(-5) + Date.now() + fileList.value[0].name;
            client.multipartUpload(fileName, fileList.value[0].raw, {...options }).then(async (file) => {
                let params = [{
                    filename: ruleForm.name,
                    videoCover: 'http://konli-klys.oss-cn-beijing.aliyuncs.com/' + file.name,
                    filesize: fileList.value[0].size,
                    fileType:1,
                    videoLength: null,
                    extension: file.name.split('.').pop().toLowerCase(),
                    url:'http://konli-klys.oss-cn-beijing.aliyuncs.com/' + file.name + '?x-oss-process=video/snapshot,t_30000,f_jpg,w_0,h_0,m_fast,ar_auto'
                }]
                const { method } = await fileUpload(params,ruleForm.dirId);
                if(method == 'success'){
                    emit('refresh');
                    closeDialog()
                    return ElMessage({
                        type: 'success',
                        message: '上传成功',
                    })
                }
            });
		} else {
			console.log('error submit!', fields)
		}
	})
}

const openDialog =() => {
    // 获取可上传目录
    getDirList();
    getOssConfig();
    ruleForm.dirId = null;
    ruleForm.name = '';
    fileList.value = [];
    state.dialog.isShowDialog = true
}


const closeDialog = () => {
    state.dialog.isShowDialog = false
}
const moveToHandle = (event: any) => {
    console.log(event);
    
}

// 暴露变量
defineExpose({
	openDialog
});

</script>

<template>
    <section>
        <el-dialog title="视频上传" v-model="state.dialog.isShowDialog"  center class="borderRadius10" width="790">
            <section>
                <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px"> 
                    <el-form-item label="选择分组：" prop="dirId">
                        <el-select v-model="ruleForm.dirId" placeholder="选择上传分组" class="width305" >
                            <el-option v-for="item in state.treeData" :key="item.group" :label="item.name" :value="item.group" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="文件名称：" prop="name">
                        <el-input class="width305" v-model="ruleForm.name" placeholder="请输入文件名称" />
                    </el-form-item>
                    <el-form-item label="上传视频：" >
                        <section style="display: flex;flex-direction: column;">
                            <el-upload accept=".mp4,.m3u8,.mov,.avi,.flv,.wmv,.mpg," v-model:file-list="fileList" :limit="1" drag action="#" :auto-upload="false">
                                <el-icon><UploadFilled /></el-icon>
                                <div class="el-upload__text">
                                    将文件拖拽至此处，或点击 <em>选择文件</em>
                                </div>
                            </el-upload>
                            <el-progress :text-inside="true" :stroke-width="20" :percentage="state.percentage" v-if="state.percentage > 0 && state.percentage != 100" />
                        </section>
                    </el-form-item>
                </el-form>
                <el-row justify="center" class="mt20">
                    <el-button @click="closeDialog">取消</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
                </el-row>
            </section>
        </el-dialog>
    </section>
</template>

<style lang='scss' scoped>
// 隐藏expand 箭头


:deep(.el-upload-dragger){
	width: 550px;
    height: 260px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}
</style>